package com.etlmaster.transformer.funcs;

import java.util.Map;

import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.apache.commons.lang.StringUtils;

import com.etlmaster.executor.annotation.StepInstruction;
import com.etlmaster.executor.trans.core.Line;
import com.etlmaster.executor.trans.core.LineTransProcessor;
import com.etlmaster.executor.utils.LogWriter;
/**
 * 行级处理 脚本编辑
 * @author wugf
 * @date 2016-04-29
 */
@StepInstruction("js")
public class TransFieldScript extends LineTransProcessor {

	private String script;
	private CompiledScript jsFunc1;
	private Bindings bindings;

	public TransFieldScript(String sourceTab,String sourceCol,String targetTab,String targetCol,String changeCode,Map paramStr,Map var){
		
		super( sourceTab,sourceCol,targetTab,targetCol,changeCode, paramStr,var);
	
	
		ScriptEngineManager sem = new ScriptEngineManager();
		ScriptEngine engine = null;
		try {
			engine = sem.getEngineByName("nashorn");
			if (engine == null) {
				LogWriter.addLog("DEBUG", "创建nashorn引擎失败，未使用Jdk 8，使用默认Rhino引擎");
				engine = sem.getEngineByName("JavaScript");
			}
		} catch (Exception e) {
			LogWriter.addLog("DEBUG", "创建nashorn引擎失败，不是使用Jdk 8使用默认Rhino引擎，{}",
					e.getMessage());
			engine = sem.getEngineByName("JavaScript");
		}
		try {
			Compilable compilable = (Compilable) engine;
			bindings = engine.createBindings();
			jsFunc1 = compilable.compile(getScript());
			bindings.put("trans", this);
		} catch (ScriptException e) {
			LogWriter.addLog("ERROR", "初始化js失败，{}", e.getMessage());
		}
	}

	public String getScript() {
		return script;
	}

	public void setScript(String script) {
		this.script = script;
	}

	public void log(String text, Object... args) {
		String[] logs = new String[args.length + 2];
		logs[0] = "INFO";
		logs[1] = text;
		for (int i = 0; i < args.length; i++) {
			logs[i + 2] = (String) args[i];
		}
		LogWriter.addLog(logs);
	}
	public Number toNumber(String str){
		if(StringUtils.isNumeric(str)){
			return Long.valueOf(str);
		}else{
			LogWriter.addLog("ERROR","输入不是数字类型");
			return 0;
		}
	}

	@Override
	public void transField(Line line) {
		try {
			

			bindings.put("line", line);
			Object obj = jsFunc1.eval(bindings);
		} catch (Exception e) {
			LogWriter.addLog("ERROR", "执行js失败，{}", e.getMessage());
		}
	}

}
